import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.normal import Normal
from sklearn.neighbors import NearestNeighbors
import numpy as np 

class BasicBlock(nn.Module):
    """Basic Block for resnet 18 and resnet 34
    """

    #BasicBlock and BottleNeck block
    #have different output size
    #we use class attribute expansion
    #to distinct
    expansion = 1

    def __init__(self, in_channels, out_channels, stride=1):
        super().__init__()

        #residual function
        self.residual_function = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Conv2d(out_channels, out_channels * BasicBlock.expansion, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(out_channels * BasicBlock.expansion)
        )

        #shortcut
        self.shortcut = nn.Sequential()

        #the shortcut output dimension is not the same with residual function
        #use 1*1 convolution to match the dimension
        if stride != 1 or in_channels != BasicBlock.expansion * out_channels:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_channels, out_channels * BasicBlock.expansion, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(out_channels * BasicBlock.expansion)
            )

    def forward(self, x):
        return nn.ReLU(inplace=True)(self.residual_function(x) + self.shortcut(x))

class U_Network(nn.Module):
    def __init__(self,num_block, bn=None, full_size=True):
        super(U_Network, self).__init__()
        self.bn = bn
        self.full_size = full_size
        self.in_channels = 16
        self.conv_init = self.conv_block(3,self.in_channels, kernel_size=7, stride=2, padding=3, batchnorm=True)

        # Encoder functions
        self.enc = nn.ModuleList()
        self.enc.append(self._make_layer(BasicBlock, 16, num_block[0], stride=2))
        self.enc.append(self._make_layer(BasicBlock, 32, num_block[1], stride=2))
        self.enc.append(self._make_layer(BasicBlock, 64, num_block[2], stride=2))
        self.enc.append(self._make_layer(BasicBlock, 128, num_block[3], stride=2))
        # Decoder functions
        self.dec = nn.ModuleList()
        
        self.dec.append(BasicBlock(128, 64))  # 1
        self.dec.append(BasicBlock(64*2, 32))  # 2
        self.dec.append(BasicBlock(32 * 2, 16))  # 3
        self.dec.append(BasicBlock(16*2, 16))  # 4
        self.dec.append(BasicBlock(16*2, 16))  # 5

        self.upsample = nn.Upsample(scale_factor=2, mode='bilinear')

        # One conv to get the flow field
        self.flow = nn.Conv2d(32, 2, kernel_size=3, padding=1)
        # Make flow weights + bias small. Not sure this is necessary.
        nd = Normal(0, 1e-5)
        self.flow.weight = nn.Parameter(nd.sample(self.flow.weight.shape))
        self.flow.bias = nn.Parameter(torch.zeros(self.flow.bias.shape))
        self.batch_norm = getattr(nn, "BatchNorm2d")(2)

    def conv_block(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, batchnorm=False):
        conv_fn = nn.Conv2d
        bn_fn = nn.BatchNorm2d
        if batchnorm:
            layer = nn.Sequential(
                conv_fn(in_channels, out_channels, kernel_size, stride=stride, padding=padding),
                bn_fn(out_channels),
                nn.LeakyReLU(0.2))
        else:
            layer = nn.Sequential(
                conv_fn(in_channels, out_channels, kernel_size, stride=stride, padding=padding),
                nn.LeakyReLU(0.2))
        return layer
    
    def _make_layer(self, block, out_channels, num_blocks, stride):
        """make resnet layers(by layer i didnt mean this 'layer' was the
        same as a neuron netowork layer, ex. conv layer), one layer may
        contain more than one residual block
        Args:
            block: block type, basic block or bottle neck block
            out_channels: output depth channel number of this layer
            num_blocks: how many blocks per layer
            stride: the stride of the first block of this layer
        Return:
            return a resnet layer
        """

        # we have num_block blocks per layer, the first block
        # could be 1 or 2, other blocks would always be 1
        strides = [stride] + [1] * (num_blocks - 1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_channels, out_channels, stride))
            self.in_channels = out_channels * block.expansion

        return nn.Sequential(*layers)

    def forward(self, src):
        x = self.conv_init(src)
        # Get encoder activations
        x_enc = [x]
        
        for i, l in enumerate(self.enc):
            x = l(x_enc[-1])
            x_enc.append(x)
        # Three conv + upsample + concatenate series
        y = x_enc[-1]
        for i in range(4):
            y = self.dec[i](y)
            y = self.upsample(y)
            y = torch.cat([y, x_enc[-(i + 2)]], dim=1)
        flow = self.flow(y)
        if self.full_size:
            flow = self.upsample(flow)
        return flow


class SpatialTransformer(nn.Module):
    def __init__(self, mode='bilinear'):
        super(SpatialTransformer, self).__init__()
        self.mode = mode

    def forward(self, src, flow):
        device = src.device
        n,c,h,w= src.shape
        x,y = np.meshgrid(np.arange(w),np.arange(h))
        torch_x = torch.from_numpy(x).float().to(device)
        torch_y = torch.from_numpy(y).float().to(device)
        grid = torch.stack((torch_x,torch_y),dim=0)[None,...]
        flow += grid
        flow = (flow*2-h)/h
        x = (2*x-h)/h
        y = (2*y-w)/w
        x = x.reshape(-1)
        y = y.reshape(-1)
        pts_distort = flow.permute(0,2,3,1).reshape(-1,2)
        target_p = pts_distort.cpu().detach().numpy()
        
        source_p = np.stack((x,y),axis=1)
        nbrs = NearestNeighbors(n_neighbors=4, algorithm='ball_tree').fit(target_p)
        distances, ind = nbrs.kneighbors(source_p)
        pts = torch.from_numpy(source_p).float().to(device)
        dis = 1/torch.norm(pts_distort[ind]-pts[:,None,:],dim=2)
        dis = dis/torch.sum(dis,dim=1,keepdim=True)
        value = torch.sum(dis[:,:,None]*pts[ind],dim=1)
        value = value.reshape(-1,h,w,2)
        img_trans = F.grid_sample(src,value,mode=self.mode,padding_mode='border')
        return img_trans
